package org.example.weboj.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.example.weboj.dto.AIChatRequest;
import org.example.weboj.dto.AIChatResponse;
import org.example.weboj.service.AIChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class AIChatServiceImpl implements AIChatService {
    
    private static final Logger logger = LoggerFactory.getLogger(AIChatServiceImpl.class);

    @Value("${deepseek.api.key}")
    private String apiKey;

    @Value("${deepseek.api.url}")
    private String apiUrl;

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    public AIChatServiceImpl(RestTemplate restTemplate, ObjectMapper objectMapper) {
        this.restTemplate = restTemplate;
        this.objectMapper = objectMapper;
    }

    @Override
    public AIChatResponse chat(AIChatRequest request) {
        // Input validation
        if (request == null || 
            (request.getMessage() == null || request.getMessage().isEmpty()) && 
            (request.getCode() == null || request.getCode().isEmpty())) {
            logger.warn("Empty request received");
            return AIChatResponse.builder()
                    .success(false)
                    .error("Request must contain a message or code")
                    .build();
        }
        
        try {
            logger.info("Preparing API request for DeepSeek API");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            
            // Construct the prompt based on the request
            StringBuilder prompt = new StringBuilder();
            if (request.getMessage() != null && !request.getMessage().isEmpty()) {
                prompt.append("User question: ").append(request.getMessage()).append("\n\n");
            }
            if (request.getCode() != null && !request.getCode().isEmpty()) {
                prompt.append("Code:\n").append(request.getCode()).append("\n\n");
            }
            if (request.getErrorMessage() != null && !request.getErrorMessage().isEmpty()) {
                prompt.append("Error message:\n").append(request.getErrorMessage()).append("\n\n");
            }
            if (request.getLanguage() != null && !request.getLanguage().isEmpty()) {
                prompt.append("Programming language: ").append(request.getLanguage()).append("\n\n");
            }

            requestBody.put("messages", new Object[]{
                new HashMap<String, String>() {{
                    put("role", "user");
                    put("content", prompt.toString());
                }}
            });
            // Add max tokens parameter to limit response size
            requestBody.put("max_tokens", 1000);
            // Add temperature parameter
            requestBody.put("temperature", 0.7);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            
            logger.info("Sending request to DeepSeek API: {}", apiUrl);
            
            try {
                Map<String, Object> response = restTemplate.postForObject(apiUrl, entity, Map.class);
                logger.info("Received response from DeepSeek API: {}", response);
                
                if (response != null && response.containsKey("choices")) {
                    // Handle choices as a List instead of an array
                    List<Map<String, Object>> choices = (List<Map<String, Object>>) response.get("choices");
                    if (!choices.isEmpty()) {
                        Map<String, Object> choice = choices.get(0);
                        Map<String, Object> message = (Map<String, Object>) choice.get("message");
                        String content = (String) message.get("content");
                        
                        return AIChatResponse.builder()
                                .response(content)
                                .success(true)
                                .build();
                    } else {
                        logger.warn("No choices in API response");
                        return AIChatResponse.builder()
                                .success(false)
                                .error("No response content from AI")
                                .build();
                    }
                } else {
                    logger.warn("Invalid API response structure: {}", response);
                    return AIChatResponse.builder()
                            .success(false)
                            .error("Invalid response from AI service")
                            .build();
                }
            } catch (RestClientException e) {
                logger.error("Error calling DeepSeek API: {}", e.getMessage(), e);
                return AIChatResponse.builder()
                        .success(false)
                        .error("Failed to connect to AI service: " + e.getMessage())
                        .build();
            }
                    
        } catch (Exception e) {
            logger.error("Error processing request: {}", e.getMessage(), e);
            return AIChatResponse.builder()
                    .success(false)
                    .error("Error processing request: " + e.getMessage())
                    .build();
        }
    }
} 